import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { Table, Button, Tag, notification } from 'antd'

export default function Audit() {
  const [dataSource, setdataSource] = useState([])
  const { username, roleId, region } = JSON.parse(localStorage.getItem('token'))

  useEffect(() => {
    axios.get('/news?auditState=1&_expand=category').then((res) => {
      const list = res.data
      setdataSource(
        roleId === 1
          ? list
          : [
              ...list.filter((item) => item.author === username),
              ...list.filter((item) => item.region === region && roleId === 3),
            ]
      )
    })
  }, [username, roleId, region])

  const auditList = [
    <Tag>未审核</Tag>,
    <Tag color="orange">审核中</Tag>,
    <Tag color="green">已通过</Tag>,
    <Tag color="red">未通过</Tag>,
  ]
  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title, item) => {
        return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
      },
    },
    {
      title: '作者',
      dataIndex: 'author',
      render: (author) => {
        return <span>{author}</span>
      },
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => {
        return <span>{category?.value}</span>
      },
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      render: (auditState) => {
        return auditList[auditState]
      },
    },
    {
      title: '操作',
      render: (item) => (
        <div>
          <Button type="primary" onClick={() => handleAudit(item.id, 2, 1)}>
            通过
          </Button>
          <Button type="primary" danger onClick={() => handleAudit(item.id, 3, 0)}>
            驳回
          </Button>
        </div>
      ),
    },
  ]
  const handleAudit = (id, auditState, publishState) => {
    setdataSource(dataSource.filter(item => item.id !== id))
    axios.patch(`/news/${id}`, {
      auditState, publishState
    }).then(res => {
      notification.info({
        message: "通知",
        description: `您可以到【审核管理-审核列表】中查看您的新闻的审核状态`,
        placement: "bottomRight",
      });
    })
  }
  return (
    <div>
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={{ pageSize: 10 }}
        rowKey={(item) => item.id}
      ></Table>
    </div>
  )
}
